import { ol,layerConfigDefautls } from '../constants'

const objectAssign = require('object-assign');
class Map {
   /**
   * 添加控件
   * @param control
   */
  addControl (control) {
    if (this.map && control instanceof ol.control.Control) {
      this.map.addControl(control)
    } else {
      throw new Error('不存在地图或者传入控件对象有误！')
    }
  }

  /**
   * 添加交互
   * @param interaction
   */
  addInteraction (interaction) {
    if (this.map && interaction instanceof ol.interaction.Interaction) {
      this.map.addInteraction(interaction)
    } else {
      throw new Error('不存在地图或者传入交互对象有误！')
    }
  }

  /**
   * 添加图层
   * @param layer
   */
  addLayer (layer) {
    let _this = this;
    if(Array.prototype.isPrototypeOf(layer)){
      $.each(layer,function(i,e){
        _this.map.addLayer(e)
      })
    }else{
       _this.map.addLayer(layer)
     }
  }

  /**
   *动态添加kljson 
   */
  addBaseLayer (config){
      let options = objectAssign({}, layerConfigDefautls, config);
      let layer = this._getLayer(options);
      this.addLayer(layer);
	    return layer;
	}

   /**
	 * 通过json对象构造点要素
	 * @param jPoint 构造点要素的json对象，结构如下：
	 * {coord: [lng, lat],
	 *  id: 'id', //要素id
	 *  style: {type: 'icon', //表示用图标渲染点要素
	 *  		src: 'fdata/image/XX.png', //图标来源
	 *  		rotation: 0.5, //旋转角度，单位：弧度
	 *  		offset: [10, 10], //相对点位的偏移量，单位：像素
	 *  		} | 
	 *  		{	type: 'circle', //表示用圆渲染点要素
	 *  			radius: 7, //圆半径
	 *  			fcolor: 'red'|'rgba(r, g, b, a)', //填充颜色
	 *  			scolor: 'green'|'rgba(r, g, b, a)', //轮廓颜色
	 *  			width: 2, //轮廓宽度
	 *  			lineDash: [1, 3, 5, 7] //轮廓虚线样式
	 *  		}
	 * }
	 * @returns feature 点要素
	 */
  addDynamicLayer (config,jPoint){
      let options = objectAssign({}, layerConfigDefautls, config);
      let layer = this._getLayer(options);
      let psource = new ol.source.Vector();
      if(Array.isArray(jPoint)){
        var _this = this;
        $.each(jPoint,function(index, item){
          var feature = _this.initPointFeature(item);
          psource.addFeature(feature);
          });
      }else{
        var feature = this.initPointFeature(jPoint);
        psource.addFeature(feature);
      }
      layer.setSource(psource);
      this.addLayer(layer);
      // this.map.getView().fit(psource.getExtent(),  this.map.getSize());
  }
  
 
	initPointFeature (jPoint){
		var coord = jPoint.coord, 
			style = jPoint.style;

		var feature = new ol.Feature({
			geometry: new ol.geom.Point(coord),
			id: jPoint.id,
			type:jPoint.type
		});
		feature.setStyle(this.crtStyle(style));
		return feature;
  }
  
  /**
	 * 根据json对象创建样式，结构如上函数所示
	 */
	crtStyle (style){
		var pstyle, type = style.type;
		if(type == 'icon'){
			pstyle = new ol.style.Style({
				image: new ol.style.Icon({
					src: style.src,
					rotation: style.rotation,
//					offsetOrigin:'bottom-left',
//					offset: style.offset,
					size:style.size
				})
			});
		}else if(type == 'circle'){
			pstyle = new ol.style.Style({
				image: new ol.style.Circle({
					fill: new ol.style.Fill({
						color: style.fcolor
					}),
					radius: style.radius,
					stroke: new ol.style.Stroke({
						color: style.scolor,
						width: style.width,
						lineDash: style.lineDash
					})
				})
			});
		}else if(type == 'line'){
			pstyle = new ol.style.Style({
				stroke: new ol.style.Stroke({
					color: style.color,
					width: style.width,
					lineDash: style.lineDash
				})
			})
		}else if(type == 'polygon'){
			pstyle = new ol.style.Style({
				stroke: new ol.style.Stroke({
					color: style.scolor,
					width: style.width,
					lineDash: style.lineDash
				}),
				fill: new ol.style.Fill({
					color: style.fcolor
				})
			})
		}
		
		return pstyle;
	}

  /**
   * 添加overlay
   * @param overlay
   */
  addOverlay (overlay) {
    this.map.addOverlay(overlay)
  }

  /**
   * 增加修订计数器并调用change事件
   */
  changed () {
    this.map.changed()
  }

  /**
   * 触发事件
   * @param event
   * @returns {boolean|undefined}
   */
  dispatchEvent (event) {
    return this.map.dispatchEvent(event)
  }

  /**
   * 查找像素位置最近的要素
   * @param pixel
   * @param callback
   * @param options
   * @returns {T|undefined}
   */
  forEachFeatureAtPixel (pixel, callback, options) {
    return this.map.forEachFeatureAtPixel(pixel, callback, options)
  }

  /**
   * 查找像素位置的图层
   * @param pixel
   * @param callback
   * @param optThis
   * @param optLayerFilter
   * @param optThis2
   * @returns {T|undefined}
   */
  forEachLayerAtPixel (pixel, callback, optThis, optLayerFilter, optThis2) {
    return this.map.forEachLayerAtPixel(pixel, callback, optThis, optLayerFilter, optThis2)
  }

  /**
   * 获取set的属性值
   * @param key
   */
  get (key) {
    return this.map.get(key)

  }

  /**
   * 获取使用的控件
   * @returns {ol.Collection.<ol.control.Control>}
   */
  getControls () {
    return this.map.getControls()
  }

  /**
   * 获取开启的所有交互
   * @returns {ol.Collection.<ol.interaction.Interaction>}
   */
  getInteractions () {
    return this.map.getInteractions()
  }

  /**
   * 获取像素位置对应的坐标
   * @param pixel
   * @returns {ol.Coordinate}
   */
  getCoordinateFromPixel (pixel) {
    return this.map.getCoordinateFromPixel(pixel)
  }

  /**
   * 获取坐标对应的像素
   * @param coordinate
   * @returns {ol.Pixel}
   */
  getPixelFromCoordinate (coordinate) {
    return this.map.getPixelFromCoordinate(coordinate)
  }

  /**
   * 返回事件触发位置的坐标
   * @param event
   * @returns {ol.Coordinate}
   */
  getEventCoordinate (event) {
    return this.map.getEventCoordinate(event)
  }

  /**
   * 返回事件触发位置的像素
   * @param event
   * @returns {ol.Pixel}
   */
  getEventPixel (event) {
    return this.map.getEventPixel(event)
  }

  /**
   * 获取像素位置的所有要素
   * @param pixel
   * @param options
   * @returns {Array.<ol.Feature|ol.render.Feature>}
   */
  getFeaturesAtPixel (pixel, options) {
    return this.map.getFeaturesAtPixel(pixel, options)
  }

  /**
   * 获取图层组
   * @returns {ol.layer.Group}
   */
  getLayerGroup () {
    return this.map.getLayerGroup()
  }

  /**
   * 获取地图上所有图层
   * @returns {!ol.Collection.<ol.layer.Base>}
   */
  getLayers () {
    return this.map.getLayers()
  }

  /**
   * 根据id获取Overlay
   * @param id
   * @returns {ol.Overlay}
   */
  getOverlayById (id) {
    return this.map.getOverlayById(id)
  }

  /**
   * 获取地图上所有的overlay
   * @returns {ol.Collection.<ol.Overlay>}
   */
  getOverlays () {
    return this.map.getOverlays()
  }

  /**
   * 获取属性
   * @returns {Object.<string, *>}
   */
  getProperties () {
    return this.map.getProperties()
  }

  /**
   * 获取修订计数器
   * @returns {number}
   */
  getRevision () {
    return this.map.getRevision()
  }

  /**
   * 获取地图尺寸
   * @returns {ol.Size|undefined}
   */
  getSize () {
    return this.map.getSize()
  }

  /**
   * 获取初始化地图的要素对象
   * @returns {Element|string|undefined}
   */
  getTarget () {
    return this.map.getTarget()
  }

  /**
   * 获取目标对象
   * @returns {Element}
   */
  getTargetElement () {
    return this.map.getTargetElement()
  }

  /**
   * 获取对象属性名称列表。
   * @returns {Array.<string>}
   */
  getKeys () {
    return this.map.getKeys()
  }

  /**
   * 获取视图对象
   * @returns {ol.View}
   */
  getView () {
    return this.map.getView()
  }

  /**
   * 获取用作地图视口的元素
   * @returns {Element}
   */
  getViewport () {
    return this.map.getViewport()
  }

  /**
   * 所在像素是否有要素
   * @param pixel
   * @param options
   * @returns {boolean}
   */
  hasFeatureAtPixel (pixel, options) {
    return this.map.hasFeatureAtPixel(pixel, options)
  }

  /**
   * 移除控件
   * @param control
   * @returns {ol.control.Control|undefined}
   */
  removeControl (control) {
    return this.map.removeControl(control)
  }

  /**
   * 移除交互
   * @param interaction
   * @returns {ol.interaction.Interaction|undefined}
   */
  removeInteraction (interaction) {
    return this.map.removeInteraction(interaction)
  }

  /**
   * 手动调用渲染器
   */
  render () {
    this.map.render()
  }

  /**
   * 以同步方式请求（立即渲染）
   * @param key
   * @param value
   * @param silent
   */
  renderSync (key, value, silent) {
    this.map.renderSync(key, value, silent)
  }

  /**
   * 设置图层组
   * @param layerGroup
   */
  setLayerGroup (layerGroup) {
    this.map.setLayerGroup(layerGroup)
  }

  /**
   * 设置属性值
   * @param values
   * @param silent <更新而不触发事件>
   */
  setProperties (values, silent) {
    this.map.setProperties(values, silent)
  }

  /**
   * 设置地图大小
   * @param size
   */
  setSize (size) {
    this.map.setSize(size)
  }

  /**
   * 设置地图所在目标元素
   * @param target
   */
  setTarget (target) {
    this.map.setTarget(target)
  }

  /**
   * 获取当前地图
   * @returns {ol.Map|*}
   */
  getMap () {
    return this.map
  }

  /**
   * 设置地图实例
   * @param map
   */
  setMap (map) {
    if (map && map instanceof ol.Map) {
      this.map = map
    }
  }

  /**
   * 重新设置视图
   * @param view
   */
  setView (view) {
    if (this.map && view instanceof ol.View) {
      this.map.setView(view)
    } else {
      throw new Error('不存在地图或者传入视图对象有误！')
    }
  }

  /**
   * 取消属性
   * @param key
   * @param silent
   */
  unset (key, silent) {
    this.map.unset(key, silent)
  }

  /**
   * 更新地图大小
   * @returns {ol.Map|*|null|_openlayers2.Map.default}
   */
  updateSize () {
    if (this.map) {
      this.map.updateSize()
      return this.map
    } else {
      throw new Error('未实例化地图对象！')
    }
  }

  /**
   * 根据id 获取feature
   * @param {*} lyrName 
   * @param {*} fid 
   * @param {*} field 
   */
  getFeature(lyrName,fid,field){
    var lyr=this.getLayerByLayerName(lyrName);
    var feature=null;
    var features = lyr.getSource().getFeatures();
    for(var i=0; i<features.length;i++){
      if(features[i].getProperties()[field||'ID']==fid){
        feature=features[i];
        break;
      }
    }
    return feature;
  }

  /**
   * 居中定位不放大
   * @param {*} lyrName 
   * @param {*} fid 
   * @param {*} field 与kljson对应的字段
   */
  focusAtFeatureNoZoom (lyrName,fid,field){
     var feature= this.getFeature(lyrName,fid,field);
     this.zoomAtFeature(feature);
     return feature;
  }

  /**
   * 居中定位放大
   * @param {*} lyrName 
   * @param {*} fid 
   * @param {*} field 与kljson对应的字段
   */
  focusAtFeature(lyrName,fid,field){
    var fea = this.getFeature(lyrName,fid,field);
    var l = this.setMapLevel(fea);
    this.map.getView().setZoom(l);
    this.zoomAtFeature(fea);
    return fea;
  } 

  /**
   * 根据fea设置显示层级
   * @param {*} fea 
   */
  setMapLevel(fea){
    var extent=fea.getGeometry().getExtent();
    var xx=extent[2]-extent[0];
    var yy=extent[3]-extent[1];
    if(xx>=yy){
         xx=xx;
    }else{
       xx=yy;
    }
    var level=13;
    if(0<xx && xx<=100){
        level=17;
    }
    if(xx>100 &&xx<=500){
        level=16;
    }
    if(xx>500 &&xx<=1000){
        level=15;
    }
    if(xx>1000 ){
        level=14;
    }
    return level;
}

/**
	 * [添加脉冲效果]
	 * @param {[Array]} coordinate [xy坐标]
	 */
	addPulse (coordinate) {
    if(!(this.map.pluses instanceof Array ))this.map.pluses=[];
		this.map.pluses.push(coordinate);
		this.addPluseArr();
	}
	
	addPluseArr(){
		var _this = this;
		// map.pulse方法是扩充的，需要修改
		$.each(this.map.pluses,function(index,e){
			_this.map.pulse(true,
				e, {
					amplitude: 0.5,
					duration: 400,
					style: new ol.style.Style({
						image: new ol.style.Circle({
							radius: 15,
							points: 4,
							stroke: new ol.style.Stroke({
								color: "red",
								width: 2
							})
						})
					}),
					easing: ol.easing.inAndOut
				}
			);
			_this.map.pulse(false,
				e, {
					amplitude: 0.5,
					duration: 400,
					style: new ol.style.Style({
						image: new ol.style.Circle({
							radius: 15,
							points: 4,
							stroke: new ol.style.Stroke({
								color: "red",
								width: 2
							})
						})
					}),
					easing: ol.easing.inAndOut
				}
			)
		})
	}
	
	/**
	 * [取消脉冲效果]
	 */
	stopPulse(point) {
		var pluses = this.map.pluses;
		if(pluses.length == 0 || !arguments[0]||pluses.length == 1){
			this.map.stopPulse();
		} else {
			this.removeObjWithArr(pluses,point);
			this.addPluseArr();
		}
	}
  
  /**
	* 取消脉冲
	*/
	stopPulse (point){
    if(point){
      this.map.stopPulse(point);
    }else{
      this.map.stopPulse(this.map.pluses);
      this.map.pluses = [];
    }
	}

	removeObjWithArr (_arr, _obj) {
        var length = _arr.length;
        for(var i = 0; i < length; i++)
        {
            if(_arr[i][0] == _obj[0] && _arr[i][1] == _obj[1])
            {
                if(i == 0)
                {
                    _arr.shift(); //删除并返回数组的第一个元素
                    return;
                }
                else if(i == length-1)
                {
                    _arr.pop();  //删除并返回数组的最后一个元素
                    return;
                }
                else
                {
                    _arr.splice(i,1); //删除下标为i的元素
                    return;
                }
            }
        }
    }

    /**
     * 导出地图成图片
     */
    exportMap(){
      var obj = this;
      var today = new Date();
      var date = '' + today.getFullYear() + this.getTwoLen((today.getMonth()+1)) + this.getTwoLen(today.getDate()) + this.getTwoLen(today.getHours()) + this.getTwoLen(today.getMinutes()) + this.getTwoLen(today.getSeconds());
      this.map.once('postcompose', function(event) {
              var canvas = event.context.canvas;
              if (navigator.msSaveBlob) {
                navigator.msSaveBlob(canvas.msToBlob(), 'map'+ date +'.png');
              } else {
                canvas.toBlob(function(blob) {
                  saveAs(blob, 'map'+ date +'.png');
                });
              }
            });
            this.map.renderSync();
    }

    getTwoLen(num){
      return num.toString().length==1?('0'+num):num;
    }

    /**
     *  修改图层
     */
    modifyMap(){
      this.select = new ol.interaction.Select({
          style:new ol.style.Style({
                  stroke: new ol.style.Stroke({
                    color: [0, 153, 255, 1],
                    width: 5
                  })
              }),
          wrapX: false
      });
      this.map.addInteraction(this.select);

      this.modify = new ol.interaction.Modify({
        features: this.select.getFeatures()
      });
      this.map.addInteraction(this.modify);
      this.modify.on('modifyend',function(e){
        var features = e.features.getArray();
        targetFeature = features[0];
        var wktInfo = new ol.format.WKT().writeFeature(targetFeature);
        console.log(wktInfo);
      })
  }
  
  /**
   * 根据位置来显示自定义样式的气泡
   * @param {*} position 
   * @param {*} w 
   * @param {*} h 
   */
  showOverlay (position, w,h){
		var div_infowin = position &&position.div_infowin?position.div_infowin:"div_infowin";
		if(!position)
			this.overlay.hide();
		else{
			var width=(w)?w:470;
			var height=(h)?h:320;
			var html='<div id="'+div_infowin+'" style="width:'+width+'px;height:'+height+'px;"></div>';

      // var popup = new ol.Overlay({
      //   element: document.getElementById('popup')
      // });
      this.overlay = new ol.Overlay.Popup ({
        popupClass: "default opacity8", 
        closeBox: false,
        onclose: function(){ console.log("You close the box"); },
        positioning: 'auto',
        autoPan: false,
        autoPanAnimation: { duration: 250 }
      });
      // popup.setPosition(position);
      this.map.addOverlay(this.overlay);
			this.overlay.show(position,html);
		}
  }
  
  /*
	停止多选*/
	resetDragBox(){
          if(this._select){
              this._select.getFeatures().clear();
              this.map.removeInteraction(this._select);
          }
          if(this._dragBox)
              this.map.removeInteraction(this._dragBox);
    }

    startDragBox(lyrid,fn){
        this._selectLayer=this.getLayerByLayerName(lyrid);
        this.resetDragBox();
          this._select = new ol.interaction.Select();
          this.map.addInteraction(this._select);
          this._dragBox = new ol.interaction.DragBox({
              condition: ol.events.condition.noModifierKeys
          });
          this.map.addInteraction(this._dragBox);
          this._dragBox.on('boxstart',this._dragBoxStart,this);
          this._dragBox.on('boxend',function(){
            console.log(this);
            var extent = this._dragBox.getGeometry().getExtent();
              var selectedFeatures = this._select.getFeatures();
              var properties=[];
            this._selectLayer.getSource().forEachFeatureIntersectingExtent(extent, function(feature) {
                  if(feature.getProperties)
                      properties.push(feature.getProperties());
                  selectedFeatures.push(feature);
              });
             let r = { properties,extent,selectedFeatures}
             fn(r);
          },this);
          
    }

    _dragBoxStart(){
        if(this._select){
            this._select.getFeatures().clear();
        }
    }


     /**
     * 开启绘制路线功能
     * isCloseRoadDraw 是否封路（首尾有封路图标）和每个点都有图片区分
     * roadCloseDraw 1
     * mapid
     */
    openLineString (isCloseRoadDraw,mapid){
    	var source = new ol.source.Vector();
    	var endPoint=[];
    	var arrow = '../assets/images/redCircle.png';
    	var lineWidth = 2;
    	if(isCloseRoadDraw == 1){ //是否封路绘制
    		 arrow ='../assets/images/roadClosed.png';
    		 lineWidth=  12;
    	}
      var styleFunction = function(feature) {
            var geometry = feature.getGeometry();
            var imageStyle =  new ol.style.Icon({
              crossOrigin: '*',
              src: arrow,
              anchor: [0.75, 0.5],
              rotateWithView: true
            });
          var firstPointStyle =  new ol.style.Style({
              stroke: new ol.style.Stroke({
                lineDash:[1,2,3,4,5,6],
                  color: '#f41800',
                  width: lineWidth
                }),
              });
            
          if(isCloseRoadDraw == 1){
            firstPointStyle =  new ol.style.Style({ //绘制成路段后路段的样式
                                  stroke: new ol.style.Stroke({
                                          color: "#000000",
                                          width: 12,
                                          lineDash:[1, 20, 4, 5]
                                      }),
                                  });
          }
              
          var styles = [firstPointStyle];  // linestring

          geometry.forEachSegment(function(start, end) {
            if(isCloseRoadDraw == 1){// 只会给最后点添加样式
              if(styles.length == 1){
                styles.push(new ol.style.Style({
                        geometry: new ol.geom.Point(start),
                        image:imageStyle
                      }));
              }
                
            }else{
              styles.push(new ol.style.Style({
                  geometry: new ol.geom.Point(end),
                  image:imageStyle
                }));
              styles.push(new ol.style.Style({
                geometry: new ol.geom.Point(start),
                image:imageStyle
              }));
            }
            endPoint = end;
          });
          if(isCloseRoadDraw == 1){
            //道路封路首尾带图标的控制（针对内涝调度绘制）
            styles.push(new ol.style.Style({
                  geometry: new ol.geom.Point(endPoint),
                  image:imageStyle
                }));
          }
          return styles;
     };
       
      var vector = new ol.layer.Vector({
        source: source,
        style: styleFunction,
      });
      
      //线段文字标注
      var style = new ol.style.Style({
          text: new ol.style.Text({
            font: 'bold 15px "Open Sans", "Arial Unicode MS", "sans-serif"',
            placement: 'line',
            fill: new ol.style.Fill({
              color: 'white'
            })
          })
        });
      var textPre =  "";
      var textVector = new ol.layer.Vector({
          source:source,
          style: function(feature) {
            style.getText().setText(textPre);
            return style;
      }});
        
      if(isCloseRoadDraw != 1){
      //绘制后形成的路段带灰色的背景图层
        var styleFunction2 = function(feature) {
              var geometry = feature.getGeometry();
              var styles = [
                // linestring
                new ol.style.Style({
                  stroke: new ol.style.Stroke({
                    color: '#b0b4b7',
                    width: 13
                  })
                })
              ];

              return styles;
            };
        var vector2 = new ol.layer.Vector({
            source: source,
            style: styleFunction2
          });
        this.addLayer(vector2);
      }
        
      this.addLayer(vector);
      this.addLayer(textVector);
      
      var styleCloseRoadDraw = {}
      if(isCloseRoadDraw == 1){ //是否封路绘制-勾画线段样式
        styleCloseRoadDraw = new ol.style.Style({
                    stroke: new ol.style.Stroke({
                    color: "#000000",
                    width: 12,
                    lineDash:[1, 10, 4, 5]
                }),
              image:new ol.style.Icon({
                crossOrigin: '*',
                src: arrow,
                anchor: [0.75, 0.5],
                rotateWithView: true
              })
            })
      }else{
        styleCloseRoadDraw = new ol.style.Style({
              stroke: new ol.style.Stroke({
                color: 'red',
                width: 5
              })
            })
      }
      var draw = new ol.interaction.Draw({
          source: source,
          type: 'LineString',
        style:styleCloseRoadDraw
        });
      this.map.draw = draw;
      this.map.sourceByDraw = source;
      this.map.addInteraction(draw);
      
      var listener;
      //XXX:不需要监听此方法
      draw.on('drawstart',
          function(evt) {
          }, this);

      draw.on('drawend',
          function(h) {
            var pointArray = h.target.a;
            this.showPopupOverlay(pointArray[pointArray.length-1],'','popup-black-drawclose',true,true,'ol-popup-black-drawclose',h.feature,mapid);
            ol.Observable.unByKey(listener);
            if(!this.map.pointArrays||this.map.pointArrays.length==0){
              this.map.pointArrays = []; 
            }
            this.map.pointArrays.push(pointArray);
          }, this);
    }

/*
	 * position   传入overlay的坐标信息
	 * contentdata   传入popup框中的内容
	 * id    传入overlay的id
	 * triangle_ornot   是否要弹出框的小三角
	 * closer_ornot    是否要弹出框的关闭
	 * classStyle   从默认样式中选择   ['ol-popup-black',,'ol-popup-grey',,'ol-popup-white']
   * mapid 地图dom id
	 */
	showPopupOverlay (position, contentdata, id, triangle_ornot, closer_ornot, classStyle,feature,mapid) {
		
		var container = document.createElement('div');        //创建poup框方法2
		container.id = 'popup';
		container.className = classStyle;

		var content = document.createElement('div');
		content.id = 'popup-content';
		content.className = classStyle+'-content';
		
		$("#" + mapid)[0].appendChild(container);
		container.appendChild(content);
		
		var overlay = new ol.Overlay(/** @type {olx.OverlayOptions} */ ({  
			  id: id,
			  element: container,  
			  autoPan: true,  
			  autoPanAnimation: {  
			    duration: 250   //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度. 单位为毫秒（ms）  
			  }  
			})); 
		
		if(triangle_ornot){
			var conret = document.createElement('div');
			conret.id = 'popup-triangle';
			conret.className = classStyle+'-triangle';
			container.appendChild(conret);
		}
		if(closer_ornot){
			var closer = document.createElement('div');
			closer.id = 'popup-closer';
			closer.className = classStyle+'-closer';
			container.appendChild(closer);
			if(feature){
				var curDrawfeature = feature;
				var map = this.map;
			}
			closer.onclick = function() {  
				  overlay.setPosition(undefined);  
				  closer.blur();  
				  curDrawfeature && map.sourceByDraw.removeFeature(curDrawfeature);
				  return false;  
				};
		}
			  
		content.innerHTML = contentdata;  
		overlay.setPosition(position);  
		this.map.addOverlay(overlay);
	}

     /**
     * 开启地图右键功能
     * id: map id
     */
    openContextMenu (id){
    	var $contextmenuDiv = $('<div id="contextmenu_container" class="contextmenu">'+
						  		'<ul>'+
									'<li><a href="#" id="stopDraw">停止绘制</a></li>'+
									'<li><a href="#" id="beginDraw">开始绘制</a></li>'+
								'</ul>'+
							'</div>' );
    	
    	$("#" + id).append($contextmenuDiv);
    	
    	var menu_overlay = new ol.Overlay({
  			element: document.getElementById("contextmenu_container"),
  			positioning: 'center-center'
  		});
      menu_overlay.setMap(this.map);
      var _this = this;
  		$(this.map.getViewport()).on("contextmenu", function(e){
  			e.preventDefault();
  			var coordinate = _this.map.getEventCoordinate(e);
  			menu_overlay.setPosition(coordinate);
  		});
  		$(this.map.getViewport()).on("click", function(e){
  			e.preventDefault();
  			menu_overlay.setPosition(undefined);
  		});
  		
  		$("#stopDraw").on('click',function(){
  			_this.map.removeInteraction(_this.map.draw);
  			if(_this.map.sourceByDraw && _this.map.sourceByDraw.getFeatures().length>0){
	  			var drawGeometryPoint = JSON.stringify(_this.map.sourceByDraw.getFeatures()[0].getGeometry().getCoordinates()); //绘制的点
  			}
  			menu_overlay.setPosition(undefined);
  		})
  		$("#beginDraw").on('click',function(){
  			_this.map.addInteraction(_this.map.draw);
  			menu_overlay.setPosition(undefined);
  		})
    }

    /**
     * 地图导出
     * mapId  
     */
    showMapExportBtn (mapId){
    	var me = this;
        var $downloadPng = $('<div style="position: absolute;left: 1%;top: 10%;background-color:#fff;width: 43px;height:34px;" >'+
        		'<a id="export-png" class="btn btn-default"><i class="fa fa-download fa-lg"></i></a></div>');
        $("#" + mapId).append($downloadPng);
        document.getElementById('export-png').addEventListener('click', function() {
            me.map.once('postcompose', function(event) {
            	var canvas = event.context.canvas;
                if (navigator.msSaveBlob) {
                  navigator.msSaveBlob(canvas.msToBlob(), 'map.png');
                } else {
                  canvas.toBlob(function(blob) {
                    saveAs(blob, 'map.png');
                  });
                }
                var image = me.up().up().up().up().down('image[name=scheduRelease]');
                if(!image){
                	image = me.up().up().up().up().down('image[name=scheduReleaseRiver]');
                }
                image && image.setSrc(me.convertCanvasToImage(canvas).src)
            });
            map.renderSync();
          });
    }
    
   // 从 canvas 提取图片 image  
    convertCanvasToImage (canvas) {  
        //新Image对象，可以理解为DOM  
        var image = new Image();  
        // canvas.toDataURL 返回的是一串Base64编码的URL，当然,浏览器自己肯定支持  
        // 指定格式 PNG  
        image.src = canvas.toDataURL("image/png");  
        return image;  
    }


}

export default Map
